<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      :title="t('routes.demo.partManager.productStructurePage.adjustSubPartOrder')"
      @register="register"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :destroyOnClose="true"
      :minHeight="600"
      :width="1000"
    >
      <BasicTree :treeData="treeData" :toolbar="true" :search="true" draggable @drop="onDrop" />
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicTree } from '/@/components/Tree/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';

  const { t } = useI18n();
  const { createMessage } = useMessage();
  const treeData = ref([
    {
      title: 'Node1',
      key: '0-0',
      children: [
        {
          title: 'Node1-1',
          key: '0-0-0',
          children: [{ title: 'Node1-1-1', key: '0-0-0-0' }],
        },
        { title: 'Node1-2', key: '0-0-1' },
      ],
    },
    {
      title: 'Node2',
      key: '0-1',
      children: [
        { title: 'Node2-1', key: '0-1-0' },
        { title: 'Node2-2', key: '0-1-1' },
      ],
    },
  ]);

  const handleSubmit = () => {
    handleCancel();
  };

  const handleCancel = () => {
    closeModal();
  };

  const onDrop = (info) => {
    console.log(info);
    const dropKey = info.node.eventKey;
    const dragKey = info.dragNode.eventKey;
    const dropPos = info.node.pos.split('-');
    const dragPos = info.dragNode.pos.split('-');

    // Check if the drag and drop are on the same level
    if (dropPos.length !== dragPos.length) {
      createMessage.warning('您只能拖放同一级别内的节点。');
      return;
    }

    const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
    const loop = (data, key, callback) => {
      data.forEach((item, index, arr) => {
        if (item.key === key) {
          return callback(item, index, arr);
        }
        if (item.children) {
          return loop(item.children, key, callback);
        }
      });
    };

    const data = [...treeData.value];

    // Find dragObject
    let dragObj = {};
    loop(data, dragKey, (item, index, arr) => {
      arr.splice(index, 1);
      dragObj = item;
    });

    // Restrict dropping as a child of another node
    if (!info.dropToGap) {
      createMessage.warning('您不能将一个节点放入另一个节点。');
      // Restore the drag object back to its original position
      loop(data, dragKey.substring(0, dragKey.lastIndexOf('-')), (item) => {
        item.children = item.children || [];
        item.children.push(dragObj);
      });
      return;
    }

    // Handle valid same-level drop positions
    let ar = [];
    let i = 0;
    loop(data, dropKey, (item, index, arr) => {
      ar = arr;
      i = index;
    });
    if (dropPosition === -1) {
      ar.splice(i, 0, dragObj);
    } else {
      ar.splice(i + 1, 0, dragObj);
    }

    treeData.value = data;
  };

  // 初始化弹窗
  const [register, { setModalProps, closeModal }] = useModalInner(() => {
    setModalProps({ confirmLoading: false });
  });
</script>

<style scoped></style>
